import 'dart:async';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_love/global/global.dart';
import 'package:flutter_love/net/dio_manager.dart';
import 'package:flutter_love/utils/page_route_util.dart';
import 'package:flutter_love/utils/progress_dialog_util.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginView extends StatefulWidget {
  const LoginView({Key? key}) : super(key: key);

  @override
  _LoginViewState createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  late TextEditingController _controllerAccount;
  late TextEditingController _controllerPassWord;
  late FocusNode _focusNodeAccount;
  late FocusNode _focusNodePassWord;
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    _controllerAccount = TextEditingController();
    _controllerPassWord = TextEditingController();
    _focusNodeAccount = FocusNode();
    _focusNodePassWord = FocusNode();
    _prefs.then((value) {
      _controllerAccount.text = value.getString('username')!;
      _controllerPassWord.text = value.getString('password')!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        centerTitle: true,
        elevation: 10,
      ),
      body: Padding(
          padding: const EdgeInsets.all(10),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Image.asset(
                  "assets/images/main.jpg",
                  width: double.infinity,
                  height: ScreenUtil.getScreenH(context) / 3,
                  fit: BoxFit.fill,
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _controllerAccount,
                  focusNode: _focusNodeAccount,
                  decoration: InputDecoration(
                      labelText: '账号',
                      hintText: '请输入账号',
                      prefixIcon: const Icon(Icons.person),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _controllerAccount.clear();
                        },
                        icon: const Icon(Icons.close),
                      )),
                  keyboardType: TextInputType.text,
                  textInputAction: TextInputAction.next,
                ),
                const SizedBox(height: 10),
                TextField(
                  obscureText: true,
                  controller: _controllerPassWord,
                  focusNode: _focusNodePassWord,
                  decoration: InputDecoration(
                      labelText: '密码',
                      hintText: '请输入密码',
                      prefixIcon: const Icon(Icons.lock),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _controllerPassWord.clear();
                        },
                        icon: const Icon(Icons.close),
                      )),
                  keyboardType: TextInputType.text,
                  textInputAction: TextInputAction.send,
                  onSubmitted: (value) {
                    LogUtil.e(value);
                  },
                ),
                const SizedBox(height: 15),
                GestureDetector(
                  onTap: () {
                    pushName(context, Global.routeBackPsd);
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    alignment: Alignment.topRight,
                    child: const Text(
                      '找回密码?',
                      style: TextStyle(color: Colors.red),
                    ),
                  ),
                ),
                const SizedBox(height: 15),
                SizedBox(
                  width: ScreenUtil.getScreenH(context),
                  child: ElevatedButton(
                    onPressed: () {
                      _login();
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.red),
                      foregroundColor: MaterialStateProperty.all(Colors.white),
                    ),
                    child: const Text('登录'),
                  ),
                ),
                SizedBox(
                  width: ScreenUtil.getScreenH(context),
                  child: ElevatedButton(
                    onPressed: () {
                      pushName(context, Global.routeRegister);
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      foregroundColor: MaterialStateProperty.all(Colors.red),
                    ),
                    child: const Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: Text(
                        '注册',
                        style: TextStyle(color: Colors.red),
                      ),
                    ),
                  ),
                )
              ],
            ),
          )),
    );
  }

  ///登录
  void _login() {
    if (_controllerAccount.text.isEmpty) {
      Fluttertoast.showToast(msg: '请输入账号', toastLength: Toast.LENGTH_SHORT);
      return;
    }
    if (_controllerPassWord.text.isEmpty) {
      Fluttertoast.showToast(msg: '请输入密码', toastLength: Toast.LENGTH_SHORT);
      return;
    }
    ProgressDialogUtil.showProgress(context);
    DioManager.getInstance()
        ?.post('/user/login', {'username': _controllerAccount.text, 'password': _controllerPassWord.text}, (data) {
      ProgressDialogUtil.dismiss(context);
      _prefs.then((value) {
        value.setString('username', _controllerAccount.text);
        value.setString('password', _controllerPassWord.text);
      });
      Navigator.of(context).pop();
      pushName(context, Global.routeMenu);
    }, (error) {
      ProgressDialogUtil.dismiss(context);
    });
  }
}
